var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var production = process.env.NODE_ENV === 'production';
var ExtractPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var plugins = [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor', // Move dependencies to our main file
    filename: '[name].js',
    children: true, // Look for common dependencies in all children,
    minChunks: 2 // How many times a dependency must come up before being extracted
  })
];

plugins = plugins.concat([
  new ExtractPlugin('bundle.css', {allChunks: true}), // <=== where should content be piped
  // Cleanup the builds/ folder before
  // compiling our final assets
  new CleanPlugin('builds'),
  // This plugin looks for similar chunks and files
  // and merges them for better caching by the user
  new webpack.optimize.DedupePlugin(),

  // This plugins optimizes chunks and modules by
  // how much they are used in your app
  new webpack.optimize.OccurenceOrderPlugin(),

  // This plugin prevents Webpack from creating chunks
  // that would be too small to be worth loading separately
  new webpack.optimize.MinChunkSizePlugin({
    minChunkSize: 51200 // ~50kb
  }),

  // This plugin minifies all the Javascript code of the final bundle
  new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    compress: {
      warnings: false // Suppress uglification warnings
    }
  }),
  new webpack.DefinePlugin({
    __DEV__: production,
    'process.env': {
      BABEL_ENV: JSON.stringify(process.env.NODE_ENV)
    }
  }),
  new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html'
  })
]);

module.exports = {
  debug: !production,
  devtool: production ? false : 'eval',
  entry: './src',
  output: {
    path: 'builds',
    filename: '[name].[chunkhash].js',
    chunkFilename: '[id].[chunkhash].js',
    publicPath: './'
  },
  async: true,
  plugins: plugins,
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: /src/,
        query: {
          presets: ['es2015']
        }
      },
      {
        test: /\.scss/,
        loader: ExtractPlugin.extract('style', 'css!sass')
      },
      {
        test: /\.html/,
        loader: 'html'
      },
      {
        test:   /\.(png|gif|jpe?g|svg)$/i,
        loader: 'url',
        query: {
          limit: 10000
        }
      }
    ]
  }
};